//
//  QDMineViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/10.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit


/// 点击头像进入到的 我的个人中心界面
final class QDMineViewController: NWTableViewController,UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,NWNetWorkingUploaderAction {
    
    /// 内容的headerView
    lazy var headerView: QDMineHeaderView = {
        
        let headerView = Bundle.main.loadNibNamed("QDMineHeaderView", owner: self, options: nil)?.first! as! QDMineHeaderView

        headerView.sureButton.layer.cornerRadius = 23
        headerView.sureButton.clipsToBounds = true
        
        headerView.headerImageView.layer.cornerRadius = 60
        headerView.headerImageView.clipsToBounds = true

        
        headerView.nameTextField.delegate = self
        headerView.phoneTextField.delegate = self
        
        return headerView
    }()
    
    /// 上传
    let updateLoader = NWNetWorkingUploader()
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        navigationItem.title = "我的信息"
        
        let view = UIView()
        view.frame = CGRect(origin: .zero, size: CGSize(width: ritl_width, height: 400))
        view.addSubview(headerView)

        
        headerView.nameTextField.text = QDUserInfoModel.share.nickName
        headerView.phoneTextField.text = QDUserInfoModel.share.phone.ritl_phone
        headerView.headerImageView.kf.setImage(with: URL(string: QDUserInfoModel.share.image), placeholder: "uc_placeholder".namedImage)
        
        
        headerView.headerImageView.addUIControlHandlerTarget(self, action: #selector(headerButtonDidTap))
        headerView.sureButton.addTarget(self, action: #selector(changedNickName), for: .touchUpInside)
        

        updateLoader.url = QDStaticHostUrl + "/static/upload"
        updateLoader.fileSuffix = "png"
        updateLoader.fileName = "file"
        updateLoader.mimeType = "image/png"
        updateLoader.delegate = self
        updateLoader.fileMaxSize = 800
        updateLoader.serviceName = "file"
        updateLoader.parameters = ["token":QDUserInfoModel.share.token]
        
        headerView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        tableView.tableHeaderView = view
    }
    

    // MARK: UITextFieldDelegate
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        
        if textField == headerView.phoneTextField {
            view.showTextHUD(text: "暂不支持手机修改")
            return false
        }
        return true
    }
    
    
    /// 头像点击
    @objc func headerButtonDidTap   (){
        
        let sheetView = UIAlertController(title: "请选择", message: nil, preferredStyle: .actionSheet)
        
        sheetView.addAction(UIAlertAction(title: "相册", style: .default, handler: { (action) in
            self.presentPickerViewController(isSelect: true)//进行选择
        }))
        sheetView.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (action) in
             self.presentPickerViewController(isSelect: false)//进行拍照
        }))
        
        sheetView.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (action) in}))
        present(sheetView, animated: true, completion: nil)
    }
    
    
    /// 弹出图片选择器
    func presentPickerViewController(isSelect: Bool) {
        if !UIImagePickerController.isSourceTypeAvailable(isSelect ? .photoLibrary : .camera) {
            view.showTextHUD(text: "请在iOS“设置”-“隐私”-“相机”中打开"); return
        }
        
        let pickerViewController = RITLImagePickerController.sharedInstance(isSelect ? .photoLibrary : .camera, delegate: self)
        present(pickerViewController, animated: true, completion: nil)
        
    }
    
    // MARK: UIImagePickerControllerDelegate
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        let image = info[.originalImage]
        picker.dismiss(animated: true) {
            //上传照片
            self.updateLoader.files = [image as Any]
            //开始上传
            self.updateLoader.resumeUpdate()
            //
            self.view.showTextHUD(text: "正在上传",delayHidden: 10)
        }
    }
    
    
    // MARK: NWNetWorkingUploaderAction
    func netWorkingUploader(_ netWorkingUploader: NWNetWorkingUploader, completeWithData info: [Any]) {
        
        guard let data = info.first as? [String: Any] else {
             view.showTextHUD(text: "图片上传错误"); return
        }
        
        guard let url = data["data"] as? String else {
            view.showTextHUD(text: "图片上传错误"); return
        }
        
        view.showTextHUD(text: "图片上传成功")
        changedHeaderImage(url: url)
        
//        //开始遍历
//        for (_, data) in info.enumerated() {
//            if let item = data as? [String: Any], let url = item["data"] as? String {
//                
//            }
//        }
//        
//        
//        guard let result = info as? [String] else {
//            view.showTextHUD(text: "图片上传错误"); return
//        }
//        
//        guard let url = result.first else {
//            view.showTextHUD(text: "图片上传错误"); return
//        }
//        
//        view.showTextHUD(text: "图片上传成功")
//        changedHeaderImage(url: url)
    }
    
    
    
    func netWorkingUploader(_ netWorkingUploader: NWNetWorkingUploader, progress current: Int, fail error: Error) {
         view.showTextHUD(text: "\(error.localizedDescription)")
    }
    
    
    /// 修改头像
    @objc func changedHeaderImage(url: String){
        
        view.endEditing(true)
        
        view.showTextHUD(text: "信息修改中..")
        
        QDNetworkingManager.request(url: QDCustomerHostUrl + "/user/updateInfo", paramteres: ["imgUrl": url], success: { (msg, data) in
            
            self.view.showTextHUD(text: "修改成功")
            //更新头像
            self.headerView.headerImageView.kf.setImage(with: URL(string: url))
//            self.headerView.headerButton.kf.setImage(with: URL(string: url), for: .normal)
            //保存本地
            QDUserInfoModel.share.image = url
            QDUserInfoModel.share.saveToNativePlace()
            
            NotificationCenter.default.post(name: QDUserInfoStatusDidChangedNotificationName, object: nil)
            
            
        }) { (msg, erroType) in
            
            self.view.showTextHUD(text: msg)
        }
        
    }
    
    
    /// 修改昵称
    @objc func changedNickName(){
        
        view.endEditing(true)
        
        if QDUserInfoModel.share.nickName == headerView.nameTextField.text {
            view.showTextHUD(text: "昵称没有变化"); return
        }
        
        guard let text = headerView.nameTextField.text else {
            view.showTextHUD(text: "昵称不能为空"); return
        }
        
        if text.isEmpty {
            view.showTextHUD(text: "昵称不能为空"); return
        }
        
        view.showTextHUD(text: "信息修改中..")
        
        QDNetworkingManager.request(url: QDCustomerHostUrl + "/user/updateInfo", paramteres: ["userName": text], success: { (msg, data) in
            
            self.view.showTextHUD(text: "修改成功")
            
            //保存本地
            QDUserInfoModel.share.nickName = text
            QDUserInfoModel.share.saveToNativePlace()
            
            NotificationCenter.default.post(name: QDUserInfoStatusDidChangedNotificationName, object: nil)
            
        }) { (msg, erroType) in
            
            self.view.showTextHUD(text: msg)
        }
        
    }

}
